#!/usr/bin/bash
#
# Check all ports of T-One one by one
#

function install_package
{
    typeset pkg=${1?"*** package name"}
    sudo rpm -q $pkg > /dev/null 2>&1 || sudo yum -y install $pkg
}

function run_cmd
{
    echo "$(id -un)@$(hostname)\$ $*"
    eval "$*"
    typeset -i rc=$?
    echo "$(id -un)@$(hostname)\$"
    echo
    return $rc
}

# Note that the command 'netstat' is required
install_package "net-tools"

typeset -a svc_ports
svc_ports[0]="tone-web     8080"
svc_ports[1]="tone-agent   8081"
svc_ports[2]="tone-runner  8082"
svc_ports[3]="tone-storage 2222"
svc_ports[4]="tone-storage 8888"
svc_ports[5]="kafka        9092"
svc_ports[6]="zookeeper    2182"
svc_ports[7]="redis        6379"
svc_ports[8]="mysql        3306"

errors=${#svc_ports[@]}
for (( i = 0; i < ${#svc_ports[@]}; i++ )); do
    svc=$(echo  ${svc_ports[$i]} | awk '{print $1}')
    port=$(echo ${svc_ports[$i]} | awk '{print $2}')
    echo "# Check the port ($port) of service \"$svc\" ..."
    run_cmd "netstat -an | grep -E --color \"$port.*LISTEN\""
    (( $? == 0 )) && (( errors -= 1 ))
done

(( errors != 0 )) && echo "FAILED" || echo "PASSED"
exit $errors
